<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="栏目名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入栏目名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
<!--      <el-form-item label="权限" prop="role">-->
<!--        <el-input v-model="queryParams.role" placeholder="请输入权限" clearable @keyup.enter.native="handleQuery" />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['conlumn:conlumn:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['conlumn:conlumn:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['conlumn:conlumn:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['conlumn:conlumn:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-if="refreshTable" v-loading="loading" :data="conlumnList" @selection-change="handleSelectionChange"
      row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :default-expand-all="isExpandAll"
      :default-sort="{prop: 'orderNum', order: 'ascending'}">
      <el-table-column label="栏目名称" align="center" prop="name" width="400">
        <template slot-scope="scope">
          <span :style="{ paddingLeft: (scope.row.level || 0) * 20 + 'px' }">
            {{ scope.row.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="orderNum" width="120" />
      <!-- 选中时显示的图片列 -->
      <el-table-column label="选中图片" align="center" prop="img1" width="200">
        <template slot-scope="scope">
          <image-preview :src="scope.row.img1" :width="50" :height="50" v-if="scope.row.img1" />
          <span v-else style="color: #999;">暂无图片</span>
        </template>
      </el-table-column>
      <!-- 未选中时显示的图片列 -->
      <el-table-column label="未选中图片" align="center" prop="img2" width="200">
        <template slot-scope="scope">
          <image-preview :src="scope.row.img2" :width="50" :height="50" v-if="scope.row.img2" />
          <span v-else style="color: #999;">暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-arrow-up" @click="moveUp(scope.row)"
            v-hasPermi="['conlumn:menu:mobile']" :disabled="scope.row.orderNum <= 0" title="上移">上移
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-arrow-down" @click="moveDown(scope.row)"
            v-hasPermi="['conlumn:menu:mobile']" title="下移">下移
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['conlumn:conlumn:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['conlumn:conlumn:remove']" :disabled="scope.row.children && scope.row.children.length > 0"
            title="有子节点不能删除">删除
          </el-button>
<!--          <el-button size="mini" type="text" icon="el-icon-setting" @click="handlePermission(scope.row)"-->
<!--            v-hasPermi="['conlumn:conlumn:edit']">权限-->
<!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改栏目管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级栏目" prop="parentId">
              <treeselect v-model="form.parentId" :options="columnOptions" :normalizer="normalizer"
                placeholder="选择上级栏目" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="栏目名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入栏目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" placeholder="排序" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-input v-model="form.role" placeholder="请输入角色" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">显示</el-radio>
                <el-radio :label="0">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="选中图片" prop="img1">
              <column-image-upload
                v-model="form.img1"
                :limit="1"
                :column-id="form.id || 0"
                :image-type="1"
                v-if="open" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="未选中图片" prop="img2">
              <column-image-upload
                v-model="form.img2"
                :limit="1"
                :column-id="form.id || 0"
                :image-type="2"
                v-if="open" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 栏目权限设置对话框 -->
    <el-dialog :title="'栏目权限设置 - ' + permissionForm.columnName" :visible.sync="permissionOpen" width="600px"
      append-to-body>
      <!-- 加载状态 -->
      <div v-loading="permissionLoading" element-loading-text="加载中..." style="min-height: 200px;">
        <el-table :data="deptList" style="width: 100%" v-if="!permissionLoading">
          <el-table-column prop="deptName" label="分局名称" width="200"></el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <!-- 权限开关 -->
              <el-switch v-model="scope.row.hasPermission" active-color="#13ce66" inactive-color="#ff4949"
                @change="handlePermissionChange(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="permissionOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConlumn, getConlumn, delConlumn, addConlumn, updateConlumn, mobileColumns } from "@/api/conlumn/column-content.js";
import {
  getDepts,
  addColumnPermission,
  delColumnPermission,
  checkColumnPermission,
  listColumnPermission,
  checkDeptPermission
} from "@/api/conlumn/permission";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ColumnImageUpload from "@/components/ColumnImageUpload/index.vue";

export default {
  name: "Conlumn",
  components: { Treeselect, ColumnImageUpload },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 栏目管理表格数据
      conlumnList: [],
      // 栏目树选项
      columnOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 权限弹出层是否显示
      permissionOpen: false,
      // 权限弹出层加载状态
      permissionLoading: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        role: null
      },
      // 表单参数
      form: {},
      // 权限表单参数
      permissionForm: {
        columnId: null,
        columnName: null
      },
      // 分局列表
      deptList: [],
      // 已分配权限的分局列表
      assignedPermissions: [],
      // 父元素12的栏目组数据
      filteredColumnsGroup: [],
      // 栏目组排序对话框显示状态
      groupSortDialogVisible: false,
      // 可排序的栏目组数据
      sortableColumnsGroup: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "栏目名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 查询栏目列表
    getList() {
      this.loading = true;
      listConlumn(this.queryParams).then(response => {
        // 处理树形数据并添加层级信息
        this.conlumnList = this.handleTreeWithLevel(response.data, "id", 0);
        this.total = response.data ? response.data.length : 0;
        this.loading = false;
      });
    },
    // 处理树形数据并添加层级信息
    handleTreeWithLevel(data, id, parentId, level = 0) {
      const cloneData = JSON.parse(JSON.stringify(data));
      const tree = [];
      const map = {};

      // 添加层级信息
      cloneData.forEach(item => {
        item.level = level;
        map[item[id]] = item;
      });

      cloneData.forEach(item => {
        if (item.parentId === parentId) {
          tree.push(item);
        } else {
          const parent = map[item.parentId];
          if (parent) {
            if (!parent.children) {
              parent.children = [];
            }
            parent.children.push(item);
          }
        }
      });

      // 对根节点进行排序
      tree.sort((a, b) => {
        return (a.orderNum || 0) - (b.orderNum || 0);
      });

      // 递归排序所有子节点
      this.sortChildrenRecursively(tree);

      return tree;
    },
    // 递归排序所有子节点
    sortChildrenRecursively(nodes) {
      nodes.forEach(node => {
        if (node.children && node.children.length > 0) {
          // 对当前节点的子节点进行排序
          node.children.sort((a, b) => {
            return (a.orderNum || 0) - (b.orderNum || 0);
          });
          // 递归处理子节点的子节点
          this.sortChildrenRecursively(node.children);
        }
      });
    },
    // 树形选择器数据转换
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // 展开/折叠操作
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    // 权限设置
    handlePermission(row) {
      this.permissionForm.columnId = row.id;
      this.permissionForm.columnName = row.name;
      this.deptList = [];
      this.permissionLoading = true;
      this.permissionOpen = true;
      this.getDepts().then(() => {
        return this.getAssignedPermissions();
      }).then(() => {
        this.permissionLoading = false;
      }).catch(() => {
        this.permissionLoading = false;
      });
    },
    // 获取分局列表
    getDepts() {
      return getDepts().then(response => {
        this.deptList = response.data.map(dept => ({
          ...dept,
          hasPermission: false
        }));
        return Promise.resolve();
      });
    },
    // 获取已分配权限
    getAssignedPermissions() {
      const permissionPromises = this.deptList.map(dept => {
        return checkDeptPermission(this.permissionForm.columnId, dept.deptId).then(response => {
          this.$set(dept, 'hasPermission', response.data);
        });
      });

      return Promise.all(permissionPromises).then(() => {
        console.log('权限检查完成', this.deptList);
      }).catch(error => {
        console.error('权限检查出错', error);
        throw error;
      });
    },
    // 获取当前栏目角色
    getCurrentColumnRole() {
      const column = this.conlumnList.find(item => item.id === this.permissionForm.columnId);
      return column ? column.role : null;
    },
    // 权限变更处理
    handlePermissionChange(row) {
      const originalState = row.hasPermission;
      const currentColumnRole = this.getCurrentColumnRole();

      if (currentColumnRole === '1') {
        if (!row.hasPermission) {
          const permissionData = {
            columnId: this.permissionForm.columnId,
            deptId: row.deptId,
            deptName: row.deptName,
            permissionType: 2
          };
          addColumnPermission(permissionData)
            .then(() => {
              this.$modal.msgSuccess("权限移除成功");
              setTimeout(() => {
                this.getAssignedPermissions();
              }, 500);
            })
            .catch(() => {
              row.hasPermission = originalState;
              this.$modal.msgError("权限移除失败");
            });
        } else {
          const columnId = parseInt(this.permissionForm.columnId, 10);
          const deptId = parseInt(row.deptId, 10);
          checkColumnPermission(columnId, deptId)
            .then(response => {
              if (response.data) {
                delColumnPermission(response.data.id)
                  .then(() => {
                    this.$modal.msgSuccess("权限恢复成功");
                    setTimeout(() => {
                      this.getAssignedPermissions();
                    }, 500);
                  })
                  .catch(() => {
                    row.hasPermission = originalState;
                    this.$modal.msgError("权限恢复失败");
                  });
              } else {
                this.$modal.msgSuccess("权限恢复成功");
              }
            })
            .catch(() => {
              row.hasPermission = originalState;
            });
        }
      } else {
        if (row.hasPermission) {
          const permissionData = {
            columnId: this.permissionForm.columnId,
            deptId: row.deptId,
            deptName: row.deptName,
            permissionType: 1
          };
          addColumnPermission(permissionData)
            .then(() => {
              this.$modal.msgSuccess("权限分配成功");
              setTimeout(() => {
                this.getAssignedPermissions();
              }, 500);
            })
            .catch(() => {
              row.hasPermission = originalState;
              this.$modal.msgError("权限分配失败");
            });
        } else {
          const columnId = parseInt(this.permissionForm.columnId, 10);
          const deptId = parseInt(row.deptId, 10);
          checkColumnPermission(columnId, deptId)
            .then(response => {
              if (response.data) {
                delColumnPermission(response.data.id)
                  .then(() => {
                    this.$modal.msgSuccess("权限移除成功");
                    setTimeout(() => {
                      this.getAssignedPermissions();
                    }, 500);
                  })
                  .catch(() => {
                    row.hasPermission = originalState;
                    this.$modal.msgError("权限移除失败");
                  });
              } else {
                this.$modal.msgSuccess("权限移除成功");
              }
            })
            .catch(() => {
              row.hasPermission = originalState;
            });
        }
      }
    },
    // 取消
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: 0,
        name: null,
        orderNum: 0,
        role: null,
        status: 1,
        img1: null,
        img2: null
      };
      this.resetForm("form");
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置搜索
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 选择变化
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 新增
    handleAdd(row) {
      const query = { operationType: 'add' };
      if (row != undefined) {
        query.parentId = row.id;
      }
      this.$router.push({
        path: '/conlumn/conlumn-form/index',
        query: query
      });
    },
    // 修改
    handleUpdate(row) {
      const columnId = row.id || this.ids[0];
      this.$router.push({
        path: '/conlumn/conlumn-form/index',
        query: {
          operationType: 'edit',
          id: columnId
        }
      });
    },
    // 获取栏目树选项
    getColumnOptions() {
      listConlumn().then(response => {
        this.columnOptions = this.handleTree(response.data, "id");
      });
    },
    // 提交表单
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateConlumn(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConlumn(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 删除
    handleDelete(row) {
      const ids = row.id || this.ids;

      // 检查是否有子节点
      if (row && row.children && row.children.length > 0) {
        this.$modal.msgError("存在子节点，不允许删除");
        return;
      }

      this.$modal.confirm('是否确认删除栏目管理编号为"' + ids + '"的数据项？').then(() => {
        return delConlumn(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 导出
    handleExport() {
      this.download('conlumn/conlumn/export', {
        ...this.queryParams
      }, `conlumn_${new Date().getTime()}.xlsx`)
    },
    // 上移排序
    moveUp(row) {
      const prevRow = this.getPreviousRow(row);
      if (!prevRow) {
        this.$modal.msgWarning("已经是第一个了！");
        return;
      }

      mobileColumns([row, prevRow]).then(() => {
        this.$modal.msgSuccess("上移成功");
        this.getList();
      }).catch(() => {
        this.$modal.msgError("操作失败");
      });
    },
    // 下移排序
    moveDown(row) {
      const nextRow = this.getNextRow(row);
      if (!nextRow) {
        this.$modal.msgWarning("已经是最后一个了！");
        return;
      }

      mobileColumns([row, nextRow]).then(() => {
        this.$modal.msgSuccess("下移成功");
        this.getList();
      }).catch(() => {
        this.$modal.msgError("操作失败");
      });
    },
    // 获取上一个同级节点
    getPreviousRow(row) {
      const flatList = this.flattenTree(this.conlumnList);
      const currentIndex = flatList.findIndex(item => item.id === row.id);

      if (currentIndex <= 0) return null;

      const prevRow = flatList[currentIndex - 1];
      // 确保是同一父级
      if (prevRow.parentId === row.parentId) {
        return prevRow;
      }
      return null;
    },
    // 获取下一个同级节点
    getNextRow(row) {
      const flatList = this.flattenTree(this.conlumnList);
      const currentIndex = flatList.findIndex(item => item.id === row.id);

      if (currentIndex === -1 || currentIndex >= flatList.length - 1) return null;

      const nextRow = flatList[currentIndex + 1];
      // 确保是同一父级
      if (nextRow.parentId === row.parentId) {
        return nextRow;
      }
      return null;
    },
    // 将树形结构扁平化
    flattenTree(tree, result = []) {
      tree.forEach(node => {
        result.push(node);
        if (node.children && node.children.length > 0) {
          this.flattenTree(node.children, result);
        }
      });
      return result;
    }
  }
};
</script>
